import { computed, onMounted, reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
import { useListPage } from "@/composables/useListPage";
import rolesApi, {
  type RoleItem,
  type RoleListParams,
  type RoleListResult,
  type RolePayload
} from "@/api/access/roles";
import permissionsApi from "@/api/access/permissions";

interface RoleFilterForm {
  keyword: string;
  status: string | number;
  scope_type: string;
}

interface RoleFormModel {
  id: number;
  name: string;
  slug: string;
  description: string;
  status: number;
  scope_type: string;
}

const DEFAULT_FILTER: RoleFilterForm = {
  keyword: "",
  status: "",
  scope_type: ""
};

const DEFAULT_FORM: RoleFormModel = {
  id: 0,
  name: "",
  slug: "",
  description: "",
  status: 1,
  scope_type: "system"
};

const STATUS_OPTIONS = [
  { label: "全部状态", value: "" },
  { label: "已启用", value: 1 },
  { label: "已停用", value: 0 }
];

const SCOPE_OPTIONS = [
  { label: "系统", value: "system" },
  { label: "组织", value: "org" }
];

const columns: TableColumnList = [
  { label: "角色ID", prop: "id", width: 90 },
  { label: "角色名称", prop: "name", minWidth: 160, align: "left" },
  { label: "角色标识", prop: "slug", minWidth: 160, align: "left" },
  {
    label: "权限数量",
    prop: "permission_ids",
    width: 120,
    slot: "permissionCount"
  },
  { label: "状态", prop: "status", width: 110, slot: "status" },
  { label: "创建时间", prop: "created_at", minWidth: 180 },
  {
    label: "操作",
    prop: "operation",
    slot: "operation",
    width: 240,
    fixed: "right"
  }
];

export function useRolePage() {
  const roleDialogVisible = ref(false);
  const roleDialogTitle = ref("新增角色");
  const roleFormRef = ref<FormInstance>();
  const roleForm = reactive<RoleFormModel>({ ...DEFAULT_FORM });
  const roleSaving = ref(false);

  const permissionDialogVisible = ref(false);
  const permissionSaving = ref(false);
  const permissionOptions = ref<Array<{ key: number; label: string }>>([]);
  const permissionLoading = ref(false);
  const selectedPermissionIds = ref<Array<number>>([]);
  const currentRole = ref<RoleItem | null>(null);

  const {
    formState: filterForm,
    pagination,
    dataList,
    loading,
    onSearch,
    resetForm: resetFilter,
    handlePageChange,
    handleSizeChange
  } = useListPage<RoleFilterForm, RoleItem, RoleListResult>(
    {
      fetch: params =>
        rolesApi.fetchList({
          ...params,
          keyword: params.keyword,
          status: params.status,
          scope_type: params.scope_type
        } as RoleListParams)
    },
    DEFAULT_FILTER,
    {},
    {
      responseAdapter: response => ({
        list: response.list,
        total: response.total,
        pageSize: response.pageSize,
        currentPage: response.currentPage
      })
    }
  );

  const tableData = computed(() => dataList.value ?? []);

  const roleRules: FormRules<RoleFormModel> = {
    name: [
      { required: true, message: "请输入角色名称", trigger: "blur" },
      { min: 2, max: 40, message: "长度需在 2-40 个字符内", trigger: "blur" }
    ],
    slug: [
      { required: true, message: "请输入角色标识", trigger: "blur" },
      {
        pattern: /^[a-z][a-z0-9-_]{2,39}$/,
        message: "标识需以小写字母开头，可包含数字、-和_",
        trigger: "blur"
      }
    ],
    scope_type: [
      { required: true, message: "请选择角色范围", trigger: "change" }
    ],
    status: [{ required: true, message: "请选择状态", trigger: "change" }],
    description: [{ max: 200, message: "描述不超过 200 字", trigger: "blur" }]
  };

  const handleSearch = async () => {
    filterForm.page = 1;
    await onSearch();
  };

  const handleResetFilters = async () => {
    await resetFilter();
  };

  const resetRoleForm = () => {
    Object.assign(roleForm, { ...DEFAULT_FORM });
  };

  const openCreate = () => {
    roleDialogTitle.value = "新增角色";
    resetRoleForm();
    roleDialogVisible.value = true;
  };

  const openEdit = (row: RoleItem) => {
    roleDialogTitle.value = "编辑角色";
    resetRoleForm();
    roleForm.id = row.id;
    roleForm.name = row.name;
    roleForm.slug = row.slug || row.code;
    roleForm.description = row.description ?? "";
    roleForm.status = Number(row.status ?? 1) as 0 | 1 | number;
    roleForm.scope_type = row.scope_type ?? "system";
    roleDialogVisible.value = true;
  };

  const submitRole = async () => {
    const formRef = roleFormRef.value;
    if (!formRef) return;
    try {
      await formRef.validate();
    } catch {
      return;
    }

    const payload: RolePayload = {
      name: roleForm.name,
      slug: roleForm.slug,
      description: roleForm.description || null,
      status: roleForm.status,
      scope_type: roleForm.scope_type
    };

    roleSaving.value = true;
    try {
      if (roleForm.id === 0) {
        await rolesApi.create(payload);
        message("角色创建成功", { type: "success" });
      } else {
        await rolesApi.update(roleForm.id, payload);
        message("角色信息已更新", { type: "success" });
      }
      roleDialogVisible.value = false;
      await onSearch();
    } catch (error: any) {
      message(error?.message ?? "保存角色失败", { type: "error" });
    } finally {
      roleSaving.value = false;
    }
  };

  const handleDelete = async (row: RoleItem) => {
    try {
      await ElMessageBox.confirm(
        `确认删除角色「${row.name}」吗？`,
        "删除确认",
        {
          type: "warning",
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        }
      );
    } catch {
      return;
    }

    try {
      await rolesApi.remove(row.id);
      message("角色已删除", { type: "success" });
      await onSearch();
    } catch (error: any) {
      message(error?.message ?? "删除角色失败", { type: "error" });
    }
  };

  const ensurePermissionOptions = async () => {
    if (permissionOptions.value.length) return;
    permissionLoading.value = true;
    try {
      const list = await permissionsApi.fetchAll({ page_size: 1000 });
      permissionOptions.value = list.map(item => ({
        key: item.id,
        label: `${item.name}（${item.code}）`
      }));
    } catch (error: any) {
      message(error?.message ?? "加载权限列表失败", { type: "error" });
    } finally {
      permissionLoading.value = false;
    }
  };

  const openPermissionDialog = async (row: RoleItem) => {
    currentRole.value = row;
    await ensurePermissionOptions();
    permissionDialogVisible.value = true;
    permissionLoading.value = true;
    try {
      const selection = await rolesApi.fetchPermissions(row.id);
      selectedPermissionIds.value = selection.ids.length
        ? selection.ids
        : (row.permission_ids ?? []);
    } catch (error: any) {
      message(error?.message ?? "获取角色权限失败", { type: "error" });
      selectedPermissionIds.value = row.permission_ids ?? [];
    } finally {
      permissionLoading.value = false;
    }
  };

  const savePermissions = async () => {
    if (!currentRole.value) return;
    permissionSaving.value = true;
    try {
      await rolesApi.savePermissions(
        currentRole.value.id,
        selectedPermissionIds.value
      );
      message("权限配置已保存", { type: "success" });
      permissionDialogVisible.value = false;
      await onSearch();
    } catch (error: any) {
      message(error?.message ?? "保存权限失败", { type: "error" });
    } finally {
      permissionSaving.value = false;
    }
  };

  onMounted(async () => {
    await onSearch();
  });

  return {
    filterForm,
    pagination,
    tableData,
    columns,
    loading,
    handleSearch,
    handleResetFilters,
    handlePageChange,
    handleSizeChange,

    roleDialogVisible,
    roleDialogTitle,
    roleForm,
    roleFormRef,
    roleRules,
    roleSaving,
    openCreate,
    openEdit,
    submitRole,
    handleDelete,

    permissionDialogVisible,
    permissionOptions,
    permissionLoading,
    permissionSaving,
    selectedPermissionIds,
    openPermissionDialog,
    savePermissions,

    statusOptions: STATUS_OPTIONS,
    scopeOptions: SCOPE_OPTIONS
  };
}
